<script setup lang="ts">
import { onMounted, ref, reactive } from "vue";
import { ElCard, ElTable, ElTableColumn, ElPagination, ElButton, ElInput, ElSelect, ElOption, ElDialog, ElForm, ElFormItem, ElMessage, ElMessageBox, ElTag, ElSpace, ElCheckboxGroup, ElCheckbox, ElInputNumber } from 'element-plus'
import { Plus, Edit, Delete, Search } from '@element-plus/icons-vue'
import { questionApi } from "@/api/modules/question.api";
import type { IQuestion, QuestionType, QuestionDifficulty } from "@shared/types/question";
import { useCommonStore } from "@/store/common";

// 试题列表数据
const questionList = ref<IQuestion[]>([]);
const loading = ref(false);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(20);

// 搜索条件
const searchForm = reactive({
  keyword: '',
  type: '' as QuestionType | '',
  difficulty: '' as QuestionDifficulty | '',
  creator: ''
});

const commonStore = useCommonStore()

commonStore.header = '题目管理'


// 弹窗控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogType = ref<'create' | 'edit' | 'view'>('create')

// 表单数据
const questionForm = reactive<Partial<IQuestion>>({
  content: '',
  type: 'Select',
  options: [
    { symbol: 'A', content: '' },
    { symbol: 'B', content: '' },
    { symbol: 'C', content: '' },
    { symbol: 'D', content: '' }
  ],
  answer: [],
  score: 1,
  difficulty: '中等'
})

// 表单验证规则
const formRules = {
  content: [
    { required: true, message: '请输入题目内容', trigger: 'blur' },
    { min: 5, max: 500, message: '题目内容长度应在5-500字符之间', trigger: 'blur' }
  ],
  score: [
    { required: true, message: '请设置分值', trigger: 'blur' }
  ]
}

// 表单引用
const formRef = ref()

// 题型选项
const questionTypes = [
  { label: '单选题', value: 'Select' },
  { label: '多选题', value: 'multiSelect' },
  { label: '判断题', value: 'Judgement' }
];

// 难度选项
const difficultyOptions = [
  { label: '简单', value: '简单' },
  { label: '中等', value: '中等' },
  { label: '困难', value: '困难' }
];

// 获取试题列表
const fetchQuestionList = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    };
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (!params[key as keyof typeof params]) {
        delete params[key as keyof typeof params];
      }
    });

    const response = await questionApi.getQuestionList(params);
    questionList.value = response.data.data;
    total.value = response.data.total_records;
  } catch (error) {
    console.error('获取试题列表失败:', error);
    ElMessage.error('获取试题列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索试题
const handleSearch = () => {
  currentPage.value = 1;
  fetchQuestionList();
};

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    type: '',
    difficulty: '',
    creator: ''
  });
  currentPage.value = 1;
  fetchQuestionList();
};

// 分页变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  fetchQuestionList();
};

const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchQuestionList();
};

// 题型变化时调整选项
const handleTypeChange = (type: QuestionType) => {
  if (type === 'Judgement') {
    questionForm.options = [
      { symbol: 'A', content: '正确' },
      { symbol: 'B', content: '错误' }
    ];
  } else {
    questionForm.options = [
      { symbol: 'A', content: '' },
      { symbol: 'B', content: '' },
      { symbol: 'C', content: '' },
      { symbol: 'D', content: '' }
    ];
  }
  questionForm.answer = [];
};

// 打开弹窗
const openDialog = (type: 'create' | 'edit' | 'view', question?: IQuestion) => {
  dialogType.value = type
  dialogVisible.value = true
  
  if (type === 'create') {
    dialogTitle.value = '创建试题'
    Object.assign(questionForm, {
      content: '',
      type: 'Select',
      options: [
        { symbol: 'A', content: '' },
        { symbol: 'B', content: '' },
        { symbol: 'C', content: '' },
        { symbol: 'D', content: '' }
      ],
      answer: [],
      score: 1,
      difficulty: '中等'
    })
  } else if (type === 'edit' && question) {
    dialogTitle.value = '编辑试题'
    Object.assign(questionForm, { ...question })
  } else if (type === 'view' && question) {
    dialogTitle.value = '试题详情'
    Object.assign(questionForm, { ...question })
  }
}

// 关闭弹窗
const closeDialog = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

// 保存试题
const handleSave = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 验证选项内容
    if (questionForm.options?.some(opt => !opt.content.trim())) {
      ElMessage.error('请填写所有选项内容');
      return;
    }
    
    if (!questionForm.answer || questionForm.answer.length === 0) {
      ElMessage.error('请选择正确答案');
      return;
    }
    
    if (dialogType.value === 'create') {
      await questionApi.createQuestion({
        content: questionForm.content!,
        type: questionForm.type!,
        options: questionForm.options!,
        answer: questionForm.answer!,
        score: questionForm.score!,
        difficulty: questionForm.difficulty!
      })
      ElMessage.success('试题创建成功')
    } else {
      await questionApi.updateQuestion({ 
        id: questionForm._id!, 
        content: questionForm.content!,
        type: questionForm.type!,
        options: questionForm.options!,
        answer: questionForm.answer!,
        score: questionForm.score!,
        difficulty: questionForm.difficulty!
      })
      ElMessage.success('试题更新成功')
    }
    
    closeDialog()
    fetchQuestionList()
  } catch (error) {
    console.error('保存试题失败:', error)
    ElMessage.error('保存试题失败')
  }
}

// 删除试题
const handleDelete = async (row: IQuestion) => {
  try {
    await ElMessageBox.confirm('确定删除此试题吗？', '确认删除', {
      type: 'warning'
    });
    
    await questionApi.deleteQuestion(row._id!);
    ElMessage.success('试题删除成功');
    fetchQuestionList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除试题失败:', error);
      ElMessage.error('删除试题失败');
    }
  }
};

// 格式化答案显示
const formatAnswer = (question: IQuestion) => {
  return question.answer.map(index => question.options[index]?.symbol).join(', ');
};

// 页面加载时获取试题列表
onMounted(() => {
  fetchQuestionList();
});
</script>

<template>
  <div class="question-page">
    <!-- 搜索区域 -->
    <ElCard class="search-card">
      <div class="search-form">
        <ElSpace wrap>
          <ElInput
            v-model="searchForm.keyword"
            placeholder="搜索题目内容"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <Search />
            </template>
          </ElInput>
          
          <ElSelect
            v-model="searchForm.type"
            placeholder="选择题型"
            clearable
            style="width: 120px"
          >
            <ElOption
              v-for="item in questionTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
          
          <ElSelect
            v-model="searchForm.difficulty"
            placeholder="选择难度"
            clearable
            style="width: 120px"
          >
            <ElOption
              v-for="item in difficultyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
          
          <ElButton type="primary" :icon="Search" @click="handleSearch">
            搜索
          </ElButton>
          
          <ElButton @click="handleReset">
            重置
          </ElButton>
          
          <ElButton type="primary" :icon="Plus" @click="openDialog('create')">
            创建试题
          </ElButton>
        </ElSpace>
      </div>
    </ElCard>

    <!-- 表格区域 -->
    <ElCard class="table-card">
      <ElTable
        :data="questionList"
        :loading="loading"
        stripe
        border
        style="width: 100%"
      >
        <ElTableColumn prop="content" label="题目内容" min-width="200" show-overflow-tooltip />
        
        <ElTableColumn prop="type" label="题型" width="100">
          <template #default="{ row }">
            <ElTag :type="row.type === 'Select' ? 'primary' : row.type === 'multiSelect' ? 'success' : 'warning'">
              {{ questionTypes.find(t => t.value === row.type)?.label }}
            </ElTag>
          </template>
        </ElTableColumn>
        
        <ElTableColumn prop="difficulty" label="难度" width="100">
          <template #default="{ row }">
            <ElTag :type="row.difficulty === '简单' ? 'success' : row.difficulty === '中等' ? 'warning' : 'danger'">
              {{ row.difficulty }}
            </ElTag>
          </template>
        </ElTableColumn>
        
        <ElTableColumn prop="score" label="分值" width="80" />
        
        <ElTableColumn label="正确答案" width="120">
          <template #default="{ row }">
            {{ formatAnswer(row) }}
          </template>
        </ElTableColumn>
        
        <ElTableColumn prop="creator" label="创建者" width="120">
          <template #default="{ row }">
            {{ typeof row.creator === 'object' ? row.creator.username : row.creator }}
          </template>
        </ElTableColumn>
        
        <ElTableColumn prop="create_time" label="创建时间" width="150">
          <template #default="{ row }">
            {{ row.create_time ? new Date(row.create_time).toLocaleString() : '-' }}
          </template>
        </ElTableColumn>
        
        <ElTableColumn label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <ElSpace>
              <ElButton
                type="primary"
                size="small"
                :icon="Edit"
                @click="openDialog('edit', row)"
              >
                编辑
              </ElButton>
              
              <ElButton
                type="danger"
                size="small"
                :icon="Delete"
                @click="handleDelete(row)"
              >
                删除
              </ElButton>
            </ElSpace>
          </template>
        </ElTableColumn>
      </ElTable>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <ElPagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </ElCard>

    <!-- 创建/编辑弹窗 -->
    <ElDialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <ElForm
        ref="formRef"
        :model="questionForm"
        :rules="formRules"
        label-width="100px"
        :disabled="dialogType === 'view'"
      >
        <ElFormItem label="题目内容" prop="content">
          <ElInput
            v-model="questionForm.content"
            type="textarea"
            :rows="3"
            placeholder="请输入题目内容"
            maxlength="500"
            show-word-limit
          />
        </ElFormItem>
        
        <ElFormItem label="题型" prop="type">
          <ElSelect v-model="questionForm.type" @change="handleTypeChange">
            <ElOption
              v-for="item in questionTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>

        <ElFormItem label="选项" prop="options">
          <div class="options-container">
            <div 
              v-for="(option, index) in questionForm.options" 
              :key="index" 
              class="option-row"
            >
              <span class="option-label">{{ option.symbol }}.</span>
              <ElInput 
                v-model="option.content" 
                :placeholder="`请输入选项${option.symbol}内容`"
                :disabled="questionForm.type === 'Judgement'"
              />
            </div>
          </div>
        </ElFormItem>

        <ElFormItem label="正确答案" prop="answer">
          <ElCheckboxGroup v-model="questionForm.answer">
            <ElCheckbox 
              v-for="(option, index) in questionForm.options" 
              :key="index" 
              :label="index"
              :disabled="questionForm.type === 'Select' && questionForm.answer && questionForm.answer.length > 0 && !questionForm.answer.includes(index)"
            >
              {{ option.symbol }}. {{ option.content }}
            </ElCheckbox>
          </ElCheckboxGroup>
        </ElFormItem>

        <ElFormItem label="分值" prop="score">
          <ElInputNumber v-model="questionForm.score" :min="1" :max="10" />
        </ElFormItem>

        <ElFormItem label="难度等级" prop="difficulty">
          <ElSelect v-model="questionForm.difficulty">
            <ElOption 
              v-for="item in difficultyOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </ElSelect>
        </ElFormItem>
      </ElForm>

      <template #footer v-if="dialogType !== 'view'">
        <ElSpace>
          <ElButton @click="closeDialog">取消</ElButton>
          <ElButton type="primary" @click="handleSave">保存</ElButton>
        </ElSpace>
      </template>
    </ElDialog>
  </div>
</template>

<style scoped>
.question-page {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.options-container {
  width: 100%;
}

.option-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.option-label {
  width: 30px;
  text-align: right;
  margin-right: 12px;
  font-weight: 500;
  color: #606266;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

:deep(.el-checkbox) {
  margin-right: 0;
  align-items: flex-start;
}

:deep(.el-checkbox__label) {
  white-space: normal;
  line-height: 1.5;
}
</style>